import {
	ref,
	onMounted,
	reactive,
	getCurrentInstance,
	inject,
} from "vue";
const PAGE_SIZE = 10;
/**
 * @param {Object} options
 * @property {Function} onShow 
 * @property {Function} onLoad 
 * @property {Number} listNum 列表数量
 * @property {Function} loadDataHandler{curListIndex} 各列表获取数据获取参数的方法
 * @property {Function} loadFilter 数据过滤方法
 * @property {Function} setup 原页面的setup方法，但有3个参数
 * 	@param {Object} pagingSetting 
 * 		@property {Number} curListIndex
 *  	@property {Function} pagingLoad
 *  	@property {Object} pagingObj
 *  	@property {Boolean} isPulling
 *  	@property {Function} deleteItem
 *  	@property {Function} setHandler
 * 	@param {Object} props 
 * 	@param {Object} ctx 
 * @return {Object}
 */
export default function(options) {
	options = Object.assign({
		listNum: 1
	}, options);
	return {
		props: options.props || {},
		components: options.components || {},
		onShow() {
			options.onShow && options.onShow.call(this);
		},
		onLoad(opts) {
			options.onLoad && options.onLoad.call(this, opts);
		},
		onPullDownRefresh(e) {
			options.onPullDownRefresh && options.onPullDownRefresh.call(this);
			this.defaultHandlePullDown();
		},
		onReachBottom() {
			this.pagingLoadNext();
			// const pagingStatus = this.pagingObj['status' + this.curListIndex];
			// if (pagingStatus === 'loading' || pagingStatus === 'no-more' || this.isPulling) return;
			// this.pagingObj['curPage' + this.curListIndex]++;
			// this.pagingLoad();
		},
		setup(props, ctx) {
			const {
				proxy
			} = getCurrentInstance();
			function defaultHandlePullDown() {
				if (pagingObj['status' + curListIndex.value] === 'loading') {
					uni.stopPullDownRefresh();
					return;
				}
				pagingLoad(true);
			}
			//处理根组件的onPullDownRefresh onReachBottom
			const handlePullDown = inject("handlePullDown", null);
			if (handlePullDown && !handlePullDown.value) {
				handlePullDown.value = () => {
					options.onPullDownRefresh && options.onPullDownRefresh.call(proxy);
					defaultHandlePullDown();
				};
			}
			const handleReachBottom = inject("handleReachBottom", null);
			if (handleReachBottom && !handleReachBottom.value) {
				handleReachBottom.value = () => {
					pagingLoadNext();
				};
			}
			//当前的tabIndex
			let curListIndex = ref(0);
			let pagingObj = {};
			for (let i = 0; i < options.listNum; i++) {
				pagingObj['status' + i] = "loading";
				pagingObj['curPage' + i] = 1;
				pagingObj['data' + i] = [];
				pagingObj['err' + i] = false;
			}
			pagingObj = reactive(pagingObj);
			const isPulling = ref(false);

			function mySplice() {
				pagingObj['data' + curListIndex.value].splice.apply(pagingObj['data' + curListIndex.value],
					arguments);
				pagingObj['data' + curListIndex.value] = [...pagingObj['data' + curListIndex.value]];
			}
			/**
			 * @param {Boolean} isPullLoad 是否下拉刷新 是的话则是从第一页开始重新加载
			 * @param {Number} targetPageNum 若指定 则刷新指定页数据
			 */
			async function pagingLoad(isPullLoad, targetPageNum) {
				pagingObj["err" + curListIndex.value] = false;
				if (isPullLoad) {
					pagingObj['curPage' + curListIndex.value] = 1;
					isPulling.value = true;
				} else {
					pagingObj['status' + curListIndex.value] = "loading";
				}
				let param = {
					pageNo: targetPageNum || pagingObj['curPage' + curListIndex.value],
					pageSize: PAGE_SIZE,
					// model: {},
					// order: "descending",
					// sort: "",
				};
				if (mySetupResult.getSearchModel) {
					const searchModel = mySetupResult.getSearchModel();
					Object.assign(param, searchModel);
				}
				if (mySetupResult.getExtraParam) {
					Object.assign(param, mySetupResult.getExtraParam() || {});
				}
				const resp = await options['loadDataHandler' + curListIndex.value].call(proxy, param);
				if (resp) {
					// resp.records = []
					let records = resp.list;
					if (options.loadFilter) {
						records = await options.loadFilter.call(proxy, curListIndex.value, records);
					}
					if (isPullLoad) {
						pagingObj['data' + curListIndex.value] = resp.list;
						isPulling.value = false;
						uni.stopPullDownRefresh();
					} else {
						if (targetPageNum) {
							const start = PAGE_SIZE * (targetPageNum - 1);
							mySplice(start, PAGE_SIZE, ...resp.list);
						} else {
							pagingObj['data' + curListIndex.value] = pagingObj['data' + curListIndex.value]
								.concat(resp.list);
						}
					}
					ctx.emit("loadPagingData",{
						data: pagingObj['data' + curListIndex.value],
						index: curListIndex.value,
						newData: records,
					});
					const len = pagingObj['data' + curListIndex.value].length;
					if (len > 0 && len < resp.total) {
						pagingObj['status' + curListIndex.value] = 'more';
					} else {
						pagingObj['status' + curListIndex.value] = "no-more";
					}
				} else {
					ctx.emit("loadPagingData",{
						data: [],
						index: curListIndex.value,
						newData: [],
						isErr: true,
					});
					pagingObj["err" + curListIndex.value] = true;
					pagingObj['status' + curListIndex.value] = 'no-more';
				}
			}
			async function deleteItem(index) {
				const start = (pagingObj['curPage' + curListIndex.value] - 1) * PAGE_SIZE;
				if (index >= start) {
					//所删的项在最后一页
					if (index === start && index === pagingData.value.length - 1) {
						//最后一页只有一项
						pagingObj['curPage' + curListIndex.value]--;
						mySplice(index, 1);
						return;
					}
					if (pagingObj['status' + curListIndex.value] === 'no-more') {
						//没有更多数据
						mySplice(index, 1);
						return;
					}
				}
				mySplice(index, 1);
				//最后一页重新加载
				await pagingLoad(false, pagingObj['curPage' + curListIndex.value]);
			}
			async function pagingLoadNext() {
				const pagingStatus = pagingObj['status' + curListIndex.value];
				if (pagingStatus === 'loading' || pagingStatus === 'no-more' || isPulling.value) return;
				pagingObj['curPage' + curListIndex.value]++;
				await pagingLoad();
			}
			/**
			 * 根据id值获取id所在的页码
			 */
			function getPageIndexById(id, key, pageSize) {
				if (!pageSize) {
					pageSize = PAGE_SIZE;
				}
				const data = pagingObj['data' + curListIndex.value];
				for (let i = 0; i < data.length; i++) {
					if (data[i][key] + '' === id + '') {
						const pageIndex = parseInt(i / pageSize) + 1;
						return pageIndex;
					}
				}
				return null;
			}
			const pagingSetting = {
				curListIndex,
				pagingLoad,
				pagingObj,
				isPulling,
				deleteItem,
				getPageIndexById,
				setHandler(listIndex, handler) {
					options['loadDataHandler' + listIndex] = handler;
				},
			};
			const mySetupResult = options.setup(pagingSetting, props, ctx);
			return {
				...pagingSetting,
				...mySetupResult,
				pagingLoadNext,
				defaultHandlePullDown,
			};
		}
	};
}
